﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Web.UI;
using VitCode.Castle.DataAccess;
using VitCode.Castle.Entities;

namespace VitCode.Castle.Management
{
    public class PermissionManager
    {
        private const string ADD = "Add";
        private const string EDIT = "Edit";
        private const string DELETE = "Delete";
        private const string LOGICDELETE = "LogicDelete";
        private const string AUDIT = "Audit";
        private const string HANDDEPRECIATION = "HandDepreciation";

        private const string AUTODEPRECIATION = "AutoDepreciation";

        private const string DATAIMPORT = "DataImport";

        private const string MODULEDOWNLOAD = "ModuleDownLoad";

        BaseDataManager m_Help = new BaseDataManager();
        private CastleAccess m_CastleAccess = new CastleAccess();

        private bool CheckIsAdmin(string strUserId)
        {
            return m_CastleAccess.CheckIsAdmin(strUserId);
        }

        /// <summary>
        /// 檢查登錄用戶有沒有此功能表許可權
        /// </summary>
        /// <param name="strUserId">登錄用戶ID</param>
        /// <param name="strMenuId">資源菜單ID</param>
        /// <returns></returns>
        public bool CheckMenuPermission(string strUserId, string strMenuId)
        {
            //if (CheckIsAdmin(strUserId)) return true;
            IList objList =
                m_Help.Session.CreateQuery("from UserRoleRelation r where r.UserId = '" + strUserId + "'").List();

            if (objList != null && objList.Count > 0)
            {
                for (int i = 0; i < objList.Count; i++)
                {
                    var currentUserRoleRelation = (UserRoleRelation)objList[i];
                    string strRoleId = currentUserRoleRelation.RoleId.ToString();
                    var nameValueCollection = new NameValueCollection();
                    nameValueCollection.Add("ObjId", strRoleId);
                    nameValueCollection.Add("ResourceId", strMenuId);
                    nameValueCollection.Add("ObjClassName", "Role");
                    nameValueCollection.Add("ResourceClassName", "Menu");
                    IList objList2 = m_Help.GetObjectList(new Permission().GetType().Name, nameValueCollection);
                    if (objList2 != null && objList2.Count > 0)
                    {
                        return true;
                    }
                }

            }
            return false;
        }

        private bool CheckPagePermission(Page page,string operatorString)
        { 
            string strMenuId = page.Request["MenuId"];
            if (string.IsNullOrEmpty(strMenuId))
                return false;
            return CheckOperaterPermission(page, strMenuId, operatorString);
        }

        private bool CheckOperaterPermission(Page page, string menuId, string operater)
        {
            if (GenericContext.CurrUserId  != Guid.Empty)
            {
                var userId = GenericContext.CurrUserId;
           
           // if (CheckIsAdmin(userId)) return true;
            IList objList = m_Help.GetObjectList(new UserRoleRelation().GetType().Name, "UserId", userId.ToString());
            if (objList != null && objList.Count > 0)
            {
                for (int i = 0; i < objList.Count; i++)
                {
                    var currentRoleRelation = (UserRoleRelation)objList[i];
                    string strRoleId = currentRoleRelation.RoleId.ToString();
                    if (strRoleId != null && strRoleId.Length == 36 && menuId.Trim().Length == 36)
                    {
                        var nameValueCollection = new NameValueCollection();
                        nameValueCollection.Add("ObjClassName", "Role");
                        nameValueCollection.Add("ResourceClassName", "Menu");
                        nameValueCollection.Add("ObjId", strRoleId);
                        nameValueCollection.Add("ResourceId", menuId);

                        IList permissionList = m_Help.GetObjectList(new Permission().GetType().Name, nameValueCollection);
                        if (permissionList != null && permissionList.Count > 0)
                        {
                            var currentPermission = (Permission)permissionList[0];
                            if (!string.IsNullOrEmpty(currentPermission.OperateNum))
                            {
                                string strOperate = currentPermission.OperateNum;
                                if (strOperate.Contains(operater))
                                    return true;
                            }
                        }
                    }
                }
              }
            }
            return false;
        }

        public bool CheckPageIsCanAdd(Page page)
        {
            return CheckPagePermission(page, ADD);
        }
        public bool CheckPageIsCanEdit(Page page)
        {
            return CheckPagePermission(page, EDIT);
        }
        public bool CheckPageIsCanDelete(Page page)
        {
            return CheckPagePermission(page, DELETE);
        }
        public bool CheckPageIsCanhandDepreciation(Page page)
        {
            return CheckPagePermission(page, HANDDEPRECIATION);
        }

        public bool CheckPageIsCanAutoDepreciation(Page page)
        {
            return CheckPagePermission(page, AUTODEPRECIATION);
        }

        public bool CheckPageIsCanDataImport(Page page)
        {
            return CheckPagePermission(page, DATAIMPORT);
        }

        public bool CheckPageIsCanModuleDownLoad(Page page)
        {
            return CheckPagePermission(page, MODULEDOWNLOAD);
        }



        /// <summary>
        /// 接收3個參數，判斷用戶有無操作當前資源的許可權，有則返回true.
        /// </summary>
        /// <param name="menuId">菜單ID</param>
        /// <param name="userId">登錄用戶ID</param>
        /// <param name="operater">操作:(Add,Edit,Delete,Audit,Load,Up,DataImport......)</param>
        /// <returns></returns>
        public bool CheckOperaterPermission(string menuId, string userId, string operater)
        {
            if (CheckIsAdmin(userId)) return true;
            IList objList = m_Help.GetObjectList(new UserRoleRelation().GetType().Name, "UserId", userId);
            if (objList != null && objList.Count > 0)
            {
                for (int i = 0; i < objList.Count; i++)
                {
                    var currentRoleRelation = (UserRoleRelation)objList[i];
                    string strRoleId = currentRoleRelation.RoleId.ToString();
                    if (strRoleId != null && strRoleId.Length == 36 && menuId.Trim().Length == 36)
                    {
                        var nameValueCollection = new NameValueCollection();
                        nameValueCollection.Add("ObjClassName", "Role");
                        nameValueCollection.Add("ResourceClassName", "Menu");
                        nameValueCollection.Add("ObjId", strRoleId);
                        nameValueCollection.Add("ResourceId", menuId);

                        IList permissionList = m_Help.GetObjectList(new Permission().GetType().Name, nameValueCollection);
                        if (permissionList != null && permissionList.Count > 0)
                        {
                            var currentPermission = (Permission)permissionList[0];
                            if (!string.IsNullOrEmpty(currentPermission.OperateNum))
                            {
                                string strOperate = currentPermission.OperateNum;
                                if (strOperate.Contains(operater))
                                    return true;
                            }
                        }
                    }
                }
            }
            return false;
        }



        public bool CheckPageIsCanAdd(Page page, bool IsInventory)
        {
            return CheckPagePermission(page, ADD,IsInventory);
        }

        public bool CheckPageIsCanEdit(Page page, bool IsInventory)
        {
            return CheckPagePermission(page, EDIT, IsInventory);
        }

        public bool CheckPageIsCanDelete(Page page, bool IsInventory)
        {
            return CheckPagePermission(page, DELETE, IsInventory);
        }

        private bool CheckPagePermission(Page page, string operatorString, bool IsInventory)
        {
            string strMenuId = page.Request["MenuId"];
            if (string.IsNullOrEmpty(strMenuId))
                return false;
            return CheckOperaterPermission(page, strMenuId, operatorString,IsInventory);
        }

        private bool CheckOperaterPermission(Page page, string menuId, string operater, bool IsInventory)
        {
            if(IsInventory)
            {
                if (page.Request["Inventory_LoginUserId"] != null)
                {
                    var userId = page.Request.Cookies["Inventory_LoginUserId"].Value;

                    if (CheckIsAdmin(userId)) return true;
                    IList objList = m_Help.GetObjectList(new UserRoleRelation().GetType().Name, "UserId", userId);
                    if (objList != null && objList.Count > 0)
                    {
                        for (int i = 0; i < objList.Count; i++)
                        {
                            var currentRoleRelation = (UserRoleRelation)objList[i];
                            string strRoleId = currentRoleRelation.RoleId.ToString();
                            if (strRoleId != null && strRoleId.Length == 36 && menuId.Trim().Length == 36)
                            {
                                var nameValueCollection = new NameValueCollection();
                                nameValueCollection.Add("ObjClassName", "Role");
                                nameValueCollection.Add("ResourceClassName", "Menu");
                                nameValueCollection.Add("ObjId", strRoleId);
                                nameValueCollection.Add("ResourceId", menuId);

                                IList permissionList = m_Help.GetObjectList(new Permission().GetType().Name, nameValueCollection);
                                if (permissionList != null && permissionList.Count > 0)
                                {
                                    var currentPermission = (Permission)permissionList[0];
                                    if (!string.IsNullOrEmpty(currentPermission.OperateNum))
                                    {
                                        string strOperate = currentPermission.OperateNum;
                                        if (strOperate.Contains(operater))
                                            return true;
                                    }
                                }
                            }
                        }
                    }
                }
               
            }
            return false;
        }
    
    }
}
